// 播放历史管理服务
import type { Song } from './musicApi';

export interface PlayHistoryItem extends Song {
  playTime: number; // 播放时间戳
  playCount: number; // 播放次数
}

class PlayHistoryService {
  private readonly STORAGE_KEY = 'music_play_history';
  private readonly MAX_HISTORY_SIZE = 100; // 最多保存100首历史记录

  // 获取播放历史
  getPlayHistory(): PlayHistoryItem[] {
    try {
      const historyData = localStorage.getItem(this.STORAGE_KEY);
      if (historyData) {
        const history = JSON.parse(historyData) as PlayHistoryItem[];
        // 按播放时间倒序排列
        return history.sort((a, b) => b.playTime - a.playTime);
      }
    } catch (error) {
      console.error('获取播放历史失败:', error);
    }
    return [];
  }

  // 添加到播放历史
  addToHistory(song: Song): void {
    try {
      const history = this.getPlayHistory();
      const existingIndex = history.findIndex(item => item.rid === song.rid);
      
      if (existingIndex >= 0) {
        // 如果已存在，更新播放时间和次数
        history[existingIndex].playTime = Date.now();
        history[existingIndex].playCount += 1;
      } else {
        // 如果不存在，添加新记录
        const newItem: PlayHistoryItem = {
          ...song,
          playTime: Date.now(),
          playCount: 1
        };
        history.unshift(newItem);
      }

      // 限制历史记录数量
      if (history.length > this.MAX_HISTORY_SIZE) {
        history.splice(this.MAX_HISTORY_SIZE);
      }

      // 保存到本地存储
      localStorage.setItem(this.STORAGE_KEY, JSON.stringify(history));
    } catch (error) {
      console.error('添加播放历史失败:', error);
    }
  }

  // 删除历史记录
  removeFromHistory(rid: string): void {
    try {
      const history = this.getPlayHistory();
      const filteredHistory = history.filter(item => item.rid !== rid);
      localStorage.setItem(this.STORAGE_KEY, JSON.stringify(filteredHistory));
    } catch (error) {
      console.error('删除播放历史失败:', error);
    }
  }

  // 清空播放历史
  clearHistory(): void {
    try {
      localStorage.removeItem(this.STORAGE_KEY);
    } catch (error) {
      console.error('清空播放历史失败:', error);
    }
  }

  // 获取播放次数最多的歌曲
  getMostPlayedSongs(limit: number = 10): PlayHistoryItem[] {
    const history = this.getPlayHistory();
    return history
      .sort((a, b) => b.playCount - a.playCount)
      .slice(0, limit);
  }

  // 获取最近播放的歌曲
  getRecentSongs(limit: number = 10): PlayHistoryItem[] {
    const history = this.getPlayHistory();
    return history.slice(0, limit);
  }
}

export const playHistoryService = new PlayHistoryService();